#include <windows.h>
#include "mmsystem.h"

#include "DDRunTime.h"

#pragma comment(lib, "winmm.lib")

int    TimerAccuracy;
static LARGE_INTEGER timerStartTime;
static unsigned long timerFreqKHz, timerFreqMHz;


inline unsigned long div64u(unsigned __int64 a , unsigned long d)
{
#ifdef _WIN32
	_asm
	{
		mov eax , dword ptr a
		mov edx , dword ptr a + 4
		div d
	}
#else
     return a/d;
#endif
}

void InitTimer()
{
	LARGE_INTEGER timerFreq64;
	QueryPerformanceFrequency(&timerFreq64);
	timerFreqKHz = div64u(timerFreq64.QuadPart , 1000);
	if(timerFreqKHz == 0)timerFreqKHz = 1;
	QueryPerformanceCounter(&timerStartTime);

	TIMECAPS timecaps;   
	if(timeGetDevCaps(&timecaps,sizeof(TIMECAPS))==TIMERR_NOERROR)
	{
		TimerAccuracy = min(max(timecaps.wPeriodMin,1),timecaps.wPeriodMax); 
	}

	timeBeginPeriod(TimerAccuracy);   
}

void FreeTimer()
{
	timeEndPeriod(TimerAccuracy); 
}


unsigned long DD_GetTimeStamp()
{
	LARGE_INTEGER curTime;
	QueryPerformanceCounter(&curTime);
	curTime.QuadPart -= timerStartTime.QuadPart;
	curTime.HighPart = ((unsigned)curTime.HighPart) % timerFreqKHz;
	
	//return curTime.QuadPart/timerFreqKHz;
	return div64u(curTime.QuadPart , timerFreqKHz);
}


